//
//  KRLTabBar.m
//  KaraLive
//
//  Created by Sergeant on 2018/9/10.
//  Copyright © 2018年 naxigoren. All rights reserved.
//

#import "KRLTabBar.h"

#define KRL_Tab_Bar_Button_Count 5

@interface KRLTabBar()

@property (nonatomic, weak) id<KRLTabBarDelegate> tabDelegate;
@property(nonatomic, strong) UIButton *centerButton;
@property(nonatomic, strong) UILabel *centerLabel;

@end

@implementation KRLTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.translucent = NO;

        self.centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.centerButton addTarget:self action:@selector(didClickCenterButton) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.centerButton];
        
        UILabel *label = [[UILabel alloc] init];
        self.centerLabel = label;
        label.font = [UIFont systemFontOfSize:10];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
    }
    return self;
}

- (void)didClickCenterButton {
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectCenterItem:)]) {
        [(id<KRLTabBarDelegate>)self.delegate tabBar:self didSelectCenterItem:self.centerButton];
    }
}

// 调整子视图的布局
- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat width = self.frame.size.width / KRL_Tab_Bar_Button_Count / 2;
    for (UIView *view in self.subviews) {
        if ([view isEqual:self.centerTitle]) {
            view.frame = CGRectMake(0, 0, width, 15);
            view.center = CGPointMake(self.frame.size.width/2, self.frame.size.height - view.frame.size.height + 8);
        } else if ([view isEqual:self.centerButton]) {
            view.frame = CGRectMake(0, 0, self.centerImage.size.width, self.centerImage.size.height);
            view.center = CGPointMake(self.frame.size.width/2, 10);
        }
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (self.isHidden == NO) {
        //将当前tabbar的触摸点转换坐标系，转换到中心按钮的身上，生成一个新的点
        //判断如果这个新的点是在中心按钮身上，那么处理点击事件最合适的view就是中心按钮
        CGPoint newP = [self convertPoint:point toView:self.centerButton];
        if ([self.centerButton pointInside:newP withEvent:event]) {
            return self.centerButton;
        } else {
            return [super hitTest:point withEvent:event];
        }
    } else {
        return [super hitTest:point withEvent:event];
    }
}

- (void)setCenterImage:(UIImage *)centerImage selectedImage:(UIImage *)selectedImage {
    _centerImage = centerImage;
    [self.centerButton setBackgroundImage:centerImage forState:UIControlStateNormal];
    [self.centerButton setBackgroundImage:selectedImage forState:UIControlStateSelected];
}

- (void)setCenterTitle:(NSString *)centerTitle{
    _centerTitle = centerTitle;
    self.centerLabel.text = centerTitle;
}

@end
